package br.univas.dao;

import java.util.ArrayList;
import java.util.List;

import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Transaction;
import org.neo4j.graphdb.index.Index;

import br.edu.univas.locadoragraphtcc.database.Connection;
import br.univas.to.DirectorTO;

public class DirectorDAO {
	
	private static final String INDEXKEY = "director";
	private static final String DIRECTORKEY = "name";
	private Connection conn = null;
	
	public DirectorDAO() {
		conn = Connection.getInstance();
	}

	public void saveDirectorGraph(DirectorTO director) {
		GraphDatabaseService graph = conn.newGraphDatabase();
		Index<Node> index = graph.index().forNodes(INDEXKEY);
		Node node = index.get(DIRECTORKEY, director.getName().toLowerCase()).getSingle();
		if (node == null) {
			Transaction transaction = graph.beginTx();
			try {
				node = graph.createNode();
				node.setProperty(DIRECTORKEY, director.getName().toLowerCase());
				node.setProperty("gender", director.getGender().toLowerCase());
				index.add(node, DIRECTORKEY, director.getName().toLowerCase());
				transaction.success();
				System.out.println("Diretor cadastrado");
			} catch (Exception e) {
				transaction.failure();
			} finally {
				transaction.finish();
			}
		}
		graph.shutdown();
	}

	public List<String> getAllDirector() {
		List<String> directors = new ArrayList<>();
		GraphDatabaseService graph = conn.newGraphDatabase();
		Index<Node> index = graph.index().forNodes(INDEXKEY);
		Iterable<Node> nodes = index.query(DIRECTORKEY, "*");
		for (Node node : nodes) {
			directors.add((String) node.getProperty(DIRECTORKEY));
		}
		return directors;
	}


}
